package cn.csust.net2.manager.client.module;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import cn.csust.net2.manager.client.app.App;
import cn.csust.net2.manager.client.ux.BeanGridPanel;
import cn.csust.net2.manager.shared.po.ResearchAnswer;
import cn.csust.net2.manager.shared.po.ResearchResult;
import cn.csust.net2.manager.shared.po.ResearchTitle;
import cn.csust.net2.manager.shared.service.ResearchService;
import cn.csust.net2.manager.shared.service.ResearchServiceAsync;
import cn.csust.net2.manager.shared.util.ClassForNameAble;

import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.data.BasePagingLoadConfig;
import com.extjs.gxt.ui.client.data.BaseTreeModel;
import com.extjs.gxt.ui.client.data.BeanModel;
import com.extjs.gxt.ui.client.data.ChangeEvent;
import com.extjs.gxt.ui.client.data.ChangeListener;
import com.extjs.gxt.ui.client.data.ModelData;
import com.extjs.gxt.ui.client.data.PagingLoadConfig;
import com.extjs.gxt.ui.client.data.PagingLoadResult;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.CheckChangedEvent;
import com.extjs.gxt.ui.client.event.CheckChangedListener;
import com.extjs.gxt.ui.client.event.SelectionChangedEvent;
import com.extjs.gxt.ui.client.event.SelectionChangedListener;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.store.TreeStore;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.treepanel.TreePanel;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;

@ClassForNameAble
public class Research extends BaseModule {

	//一下常量用于 标志 model 中的 key
	private final static String ANSWER = "answer";
//	private final static String ANSWERMODEL = "answerModel";
	private final static String NAME = "name";
	private final static String ID = "id";
	private final static String TITLE = "title";
	private final static String TITLEMODEL = "titleModel";
	private final static String ANSWERLIST = "answerList";
	private final static String CLASS = "class";
	private final static String TYPE = "type";
	
	
	
	private static ResearchServiceAsync researchService = GWT.create(ResearchService.class);

	public Research() {
		this.setText("调研");
		this.setId("调研");
		this.setClosable(true);
		
		this.setLayout(new FitLayout());
		this.add(getGridPanel());
		this.addStyleName("pad-text");

	}

	public BeanGridPanel<cn.csust.net2.manager.shared.po.Research> getGridPanel() {		
		final BeanGridPanel<cn.csust.net2.manager.shared.po.Research> grid = new BeanGridPanel<cn.csust.net2.manager.shared.po.Research>(new cn.csust.net2.manager.shared.po.Research(),
				researchService);
		grid.setAutoLoad(true);
		grid.setToolBar(false);
		grid.createDefault();

	
		grid.getGrid().getSelectionModel().addSelectionChangedListener(
						new SelectionChangedListener<BeanModel>() {
							@Override
							public void selectionChanged(
									SelectionChangedEvent<BeanModel> se) {
								cn.csust.net2.manager.shared.po.Research research = se.getSelectedItem().getBean();
//								initResearchWindow(research);
								showResearchTreePanel(research);
							}
						});
		return grid;
	}	
	
	
	/*
	 * 答题的树
	 */
	//因为代码改变check 也会激活checklistenner  所以加了标志
	private static boolean settingModeFlag = false; 
	
	private static List <ModelData> cacheAnswerList = new ArrayList<ModelData>(); 
	public static  void showResearchTreePanel(cn.csust.net2.manager.shared.po.Research research){
		Window window = new Window();
		window.setSize(600, 450);
		window.setScrollMode(Scroll.AUTO);
		
		final TreeStore<ModelData> treeStore = new TreeStore<ModelData>	();
		final TreePanel<ModelData> treePanel = new TreePanel<ModelData>(treeStore);
		treePanel.setDisplayProperty(NAME);
		treePanel.setCheckable(true);

		window.add(treePanel);
		
		//添加checkListener用来控制单选
		treePanel.addCheckListener(new CheckChangedListener<ModelData>(){
			@Override
			public void checkChanged(CheckChangedEvent<ModelData> event) {
				List<ModelData>  modelList = event.getCheckedSelection();
				settingModeFlag = false;
				//检查是否有新选项变动 若有 则打开调试模式
				ModelData newModel = null;
				for(ModelData model: modelList){
					if(model.get(CLASS).equals(ANSWER)){
						if(!cacheAnswerList.contains(model)){
							newModel = model;
							settingModeFlag  = true;
							cacheAnswerList.add(model);
//							System.out.println("打开调节模式======================选中新项：" + model.get(NAME));
							break;
						}
					}					
				}
				if(settingModeFlag == false ){
					//重新压入已选项,删除在cache中但是没有选择的
//					System.out.println("调节模式关闭======================");
					for(ModelData m :modelList){
						if(m.get(CLASS).equals(ANSWER)){
							if(!modelList.contains(m)){
								cacheAnswerList.remove(m);
							}
						}
						
					}
					return;
				}
				List<ModelData> answerList  =  newModel.get(ANSWERLIST);

				
				for(ModelData m : answerList){	
					if(!newModel.get(ID).equals(m.get(ID))){
						cacheAnswerList.remove(m);
						treePanel.setChecked(m, false);
						modelList.remove(m);
						System.out.println("取消选中项："+m.get(NAME));
					}
						
				}
				
				
//				//查看cache中的数据
//				for(ModelData m : cacheAnswerList){
//					System.out.println("chche中有：" + m.get("name"));
//				}

			}			
		});
		
		
		
		//加载调研内容		
		PagingLoadConfig config = new BasePagingLoadConfig();
		config.set(ResearchService.RESEARCHID, research.getResearchId());
		researchService.findResearchTitlesByPaging(config, new AsyncCallback<PagingLoadResult<ResearchTitle>>() {

			@Override
			public void onFailure(Throwable caught) {
				MessageBox.alert("onFailure", "researchTitle", null);
				
			}

			@Override
			public void onSuccess(PagingLoadResult<ResearchTitle> result) {
				for(final ResearchTitle title : result.getData()){
					PagingLoadConfig config = new BasePagingLoadConfig();
					config.set(ResearchService.RESEARCH_TITLEID, title.getTitleId());
					final List<ModelData> answerList = new ArrayList<ModelData>();
					researchService.findResearchAnswersByPaging(config, new AsyncCallback<PagingLoadResult<ResearchAnswer>>() {
						
						@Override
						public void onSuccess(PagingLoadResult<ResearchAnswer> result) {
							
							BaseTreeModel titleModel = new BaseTreeModel();
							titleModel.set(NAME, title.getQuestion());
							titleModel.set(ID, title.getTitleId());
							titleModel.set(CLASS,TITLE);
							titleModel.set(TYPE,title.getType());
							treeStore.add(titleModel, true);
							
							for(ResearchAnswer answer: result.getData()){
								BaseTreeModel answerModel = new BaseTreeModel(titleModel);
								answerList.add(answerModel);
								answerModel.addChangeListener(new ChangeListener(){

									@Override
									public void modelChanged(ChangeEvent event) {		
										if(treePanel.isChecked(event.getItem())){
											MessageBox.alert("", "选中："+event.getItem().get(NAME), null);
										}
										
									}} );
								answerModel.set(NAME, answer.getAnswer());
								answerModel.set(ID, answer.getAnswerId());
								answerModel.set(CLASS,ANSWER);
								answerModel.set(ANSWERLIST,answerList);
								answerModel.set(TITLEMODEL, titleModel);
								answerModel.set(TITLE, title);
								answerModel.set(ANSWER, answer);
								treeStore.add(titleModel,answerModel,true);
							}
							treePanel.setExpanded(titleModel, true);
						}
						
						@Override
						public void onFailure(Throwable caught) {
							MessageBox.alert("onFailure", "researchTitle", null);
							
						}
					});
				}
				
			}
		});
		
		//给窗体添加提交按钮
		window.addButton(new Button("提交", new SelectionListener<ButtonEvent>() {
			
			@Override
			public void componentSelected(ButtonEvent ce) {
				Set<ResearchResult> rSet = new LinkedHashSet<ResearchResult>();
				for(ModelData am:cacheAnswerList){
					ResearchResult rr = new ResearchResult();
					rr.setAnswer((ResearchAnswer) am.get(ANSWER));
					rr.setTitle((ResearchTitle) am.get(TITLE));
					rr.setUserId(App.getUser().getUserID());
					rSet.add(rr);
				}
				PagingLoadConfig config = new BasePagingLoadConfig();
				config.set(ResearchService.RESERACH_RESULT_SET, rSet);
				researchService.saveResearchResultsByPaging(config, new AsyncCallback<Void>() {
					
					@Override
					public void onSuccess(Void result) {
						// TODO Auto-generated method stub
						MessageBox.alert("", "保存成功", null);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						MessageBox.alert("", "保存失败", null);
						
					}
				});
				
			}
		}));

		window.show();
	}
		
}
